<?php

namespace CacheManage;


class Helper
{

    public static $driver_instance;

    const DEFAULT_DRIVER = 'Laravel';

    /**
     * 缓存的回调 处理
     *
     * @param void $name2
     * @param int $second
     *
     * @param callable $callback
     * @param array $param_arr
     * @param bool $re
     * @return mixed|null
     */
    static public function cache_call($name2, int $second, callable $callback, $param_arr = [], $re = false)
    {
        $name = md5(serialize($name2) . $second);
        if ($re || !self::getDriver()->has($name)) {
            $data = call_user_func_array($callback, $param_arr);
            self::getDriver()->set($name, $data, $second);
            return $data;
        } else {
            return self::getDriver()->get($name);
        }
    }

    /**
     * 更新标签
     * @param type $tag
     */
    static public function update_tag($tag)
    {
        $key = 'tage_' . $tag;
        $names = Cachef::get($key);
        if ($names) {
            foreach ($names as $name) {
                $ob = Cachef::get($name . '_ob');
                if ($ob instanceof AbstractCache) {
                    $ob->update();
                }
            }
        }
    }


    /**
     * 获取驱动
     * @param null $name
     * @param array $config
     * @return DriverInterface
     */
    public static function getDriver($name = null, $config = []): DriverInterface
    {
        $name = $name ?? self::DEFAULT_DRIVER;
        if (isset(self::$driver_instance[$name])) {
            return self::$driver_instance[$name];
        }

        $class = 'CacheManage\\Driver\\' . $name;
        if (!class_exists($class)) {
            throw new \Exception("不存在的驱动");
        }
        self::$driver_instance[$name] = new $class($config);
        return self::$driver_instance[$name];
    }


}
